<?php
namespace App\Services;

use App\Models\GoodsCategory;
use App\Models\HongbaoSn;
use App\Models\Order;
use App\Models\PintuanStatistics;
use App\Models\PintuanTuan;
use App\Models\PintuanTuanCJ;
use App\Models\PintuanTuanCJData;
use App\Models\PintuanTuanData;
use App\Models\PintuanTuanMS;
use App\Models\PintuanTuanMSData;
use App\Models\Topic;
use App\Models\Pintuan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 *
 * 拼团服务层
 *
 * @author maqu
 *
 */
class PintuanService extends BaseService {
//
//    /**
//     * 获取指定ID的团详情
//     *
//     * @param $user_id 用户ID
//     * @param $nav 导航   all:全部 waite:组团中 success:已成团 failuer:组团失败
//     * @param int $firstrow         第一行
//     * @param int $pagesize         每页条数
//     *
//     * @return array
//     */
//    public function getTuanList2($user_id,$nav,$firstrow,$pagesize){
//
//        $sql = "SELECT
//	        tb_order.order_id,tb_order.pintuan_id,tb_order.tuan_id,tb_order.pay_time,tb_order_goods.quantity,
//	        tb_pintuan.pintuan_logo,tb_pintuan.pintuan_name,tb_pintuan.pintuan_desc,tb_pintuan.pt_price,tb_pintuan.pintuan_type,
//            CASE tb_pintuan.pintuan_type
//	        WHEN 1
//	          THEN tb_pintuan_tuan.state
//            WHEN 2
//	          THEN tb_pintuan_ms_tuan.state
//            ELSE tb_pintuan_cj_tuan.state
//            END AS state,
//            CASE tb_pintuan.pintuan_type
//	        WHEN 1
//	          THEN tb_pintuan_tuan.rest_quantity
//            WHEN 2
//	          THEN tb_pintuan_ms_tuan.rest_quantity
//            ELSE tb_pintuan_cj_tuan.rest_quantity
//            END AS rest_quantity
//            FROM `tb_order`
//            LEFT JOIN `tb_order_goods` ON `tb_order`.`order_id` = `tb_order_goods`.`order_id`
//            LEFT JOIN `tb_pintuan` ON `tb_pintuan`.`pintuan_id` = `tb_order`.`pintuan_id`
//            LEFT JOIN `tb_pintuan_tuan` ON `tb_order`.`tuan_id` = `tb_pintuan_tuan`.`tuan_id`
//            AND `tb_order`.`extension` = 'pintuan' ";
//        $sql .= " LEFT JOIN `tb_pintuan_ms_tuan` ON `tb_order`.`tuan_id` = `tb_pintuan_ms_tuan`.`tuan_id`
//            AND `tb_order`.`extension` = 'miaosha' ";
//        $sql.= " LEFT JOIN `tb_pintuan_cj_tuan` ON `tb_order`.`tuan_id` = `tb_pintuan_cj_tuan`.`tuan_id`
//            AND `tb_order`.`extension` = 'choujiang' ";
//        $sql.= " WHERE
//                `tb_order`.`extension` <> 'normal'
//            AND `tb_order`.`status` NOT IN (".ORDER_CANCELED.", ".ORDER_SUBMITTED.", ".ORDER_PENDING.")
//            AND `tb_order`.`delflg_buyer` = false ";
//        if($nav == "all"){
//        }elseif($nav == 'waite'){
//            $sql.= " AND( `tb_pintuan_tuan`.`state` = ".TUAN_STATE_WAITE ." OR `tb_pintuan_ms_tuan`.`state` = ".TUAN_STATE_WAITE ." OR `tb_pintuan_cj_tuan`.`state` = ".TUAN_STATE_WAITE .")";
//        }elseif($nav == 'success'){
//            $sql.= " AND( `tb_pintuan_tuan`.`state` = ".TUAN_STATE_SUCCESS ." OR `tb_pintuan_ms_tuan`.`state` = ".TUAN_STATE_SUCCESS ." OR `tb_pintuan_cj_tuan`.`state` = ".TUAN_STATE_SUCCESS .")";
//        }elseif($nav == 'failure'){
//            $sql.= " AND( `tb_pintuan_tuan`.`state` = ".TUAN_STATE_FAILURE ." OR `tb_pintuan_ms_tuan`.`state` = ".TUAN_STATE_FAILURE ." OR `tb_pintuan_cj_tuan`.`state` = ".TUAN_STATE_FAILURE .")";
//        }
//        $sql .=" AND `tb_order`.`buyer_id` = $user_id
//            ORDER BY `tb_order`.`pay_time` DESC
//            LIMIT $pagesize OFFSET $firstrow";
//
//        $tuan = DB::select($sql);
//
//        if(!$tuan){
//            return $this->failure('您还未参与拼团');
//        }
//
//        $data =[];
//
//        $temp = [
//            'tuan_id' => 0,
//            'add_time' => 0,
//            'state' => 0,
//            'state_name' => '',
//            'pintuan_logo' => '',
//            'pintuan_name' => '',
//            'pintuan_desc' => '',
//            'pintuan_type' => 1,
//            'pt_price' => 0,
//            'quantity' => 0,
//            'order_id' => 0,
//            'rest_quantity' => 0,
//            'share_url' => ''
//        ];
//        foreach($tuan as $k => $item){
//            $tuan_info = $temp;
//            $tuan_info['tuan_id'] = $item->tuan_id;
//            $tuan_info['add_time'] = local_date('Y-m-d H:i:s',$item->pay_time);
//            $tuan_info['state'] = $item->state;
//            $tuan_info['state_name'] = $this->_get_tuan_state_name($item->state);
//            $tuan_info['pintuan_logo'] = complete_url($item->pintuan_logo);
//            $tuan_info['pintuan_name'] = $item->pintuan_name;
//            $tuan_info['pintuan_desc'] = $item->pintuan_desc;
//            $tuan_info['pintuan_type'] = $item->pintuan_type;
//            $tuan_info['pt_price'] = $item->pt_price;
//            $tuan_info['quantity'] = $item->quantity;
//            $tuan_info['order_id'] = $item->order_id;
//            $tuan_info['rest_quantity'] = $item->rest_quantity;
//            if($item->state == TUAN_STATE_WAITE){
//                //TODO 分享机制
//                $tuan_info['share_url'] = config('maqu.WAP_URL').'/html/tuan/tuan.html?pintuan_type='.$item->pintuan_type.'&tuan_id='.$item->tuan_id;
//            }
//            //团相关数据
//            $data[]=$tuan_info;
//            unset($tuan_info);
//        }
//
//        unset($temp);
//
//        return $this->success($data);
//
//    }

//    private function _get_tuan_state_name($state){
//        switch($state){
//            case TUAN_STATE_WAITE:
//                return '组团中';
//            case TUAN_STATE_SUCCESS:
//                return '组团成功';
//            default:
//                return '组团失败';
//        }
//    }
//
//    /**
//     * 检查是否可以参团或者已经参团
//     * @param $pintuan_id 拼团id
//     * @param $tuan_id 团id
//     * @param $user_id 用户id、
//     * @return String
//     */
//    public function checkPintuan($pintuan_id,$tuan_id,$user_id){
//
//        $pintuan =Pintuan::with('pintuanMS','pintuanCJ')->find($pintuan_id);
//
//        //如果该拼团已下架，则不可以开团参团
//        if($pintuan->if_show == PINTUAN_IF_SHOW_NO || $pintuan->del_flag == YES){
//            return "该拼团已下架，不可以开团或参团";
//        }
//
//        switch ($pintuan->pintuan_type){
//            case PINTUAN_PUTONG :
//                break;
//            case PINTUAN_MIAOSHA :
//                if(gmtime() < $pintuan->pintuanMS->start_time){
//                    return "该秒杀活动尚未开始，不可以开团或参团";
//                }
//                break;
//            case PINTUAN_CHOUJIANG :
//                if(gmtime() < $pintuan->pintuanCJ->start_time){
//                    return "该抽奖活动尚未开始，不可以开团或参团";
//                }
//                if(gmtime() > $pintuan->pintuanCJ->end_time){
//                    return "该抽奖活动已经结束，不可以开团或参团";
//                }
//                break;
//        }
//
//        //如果是参团
//        if($tuan_id >0){
//
//            switch ($pintuan->pintuan_type){
//                case PINTUAN_PUTONG :
//                    $tuan = PintuanTuan::findOrNew($tuan_id);
//                    break;
//                case PINTUAN_MIAOSHA :
//                    $tuan = PintuanTuanMS::findOrNew($tuan_id);
//                    break;
//                case PINTUAN_CHOUJIANG :
//                    $tuan = PintuanTuanCJ::findOrNew($tuan_id);
//                    break;
//            }
//            //如果剩余参团人数为0或者团状态已经不是拼团中时，不可参团
//            if($tuan->rest_quantity == 0){
//                return "该团已经满员，请开团或参加其他团";
//            }
//
//            if($tuan->state != TUAN_STATE_WAITE){
//                return "该团已拼团成功";
//            }
//
//            switch ($pintuan->pintuan_type){
//                case PINTUAN_PUTONG :
//                    $tuanData = PintuanTuanData::where("tuan_id",$tuan_id)
//                        ->where("user_id",$user_id)->first();
//                    break;
//                case PINTUAN_MIAOSHA :
//                    $tuanData = PintuanTuanMSData::where("tuan_id",$tuan_id)
//                        ->where("user_id",$user_id)->first();
//                    break;
//                case PINTUAN_CHOUJIANG :
//                    $tuanData = PintuanTuanCJData::where("tuan_id",$tuan_id)
//                        ->where("user_id",$user_id)->first();
//                    break;
//            }
//
//            //已经参加该团中，不可重复参团
//            if($tuanData){
//                return "您已经参加该团，不可重复参团";
//            }
//        }
//
//        return "";
//
//    }
//    /**
//     * 创建团/加入团
//     *
//     */
//    public function createOrEnterTuan($extension,$pintuan_id,$user_id,$order_id,$tuan_id,$quantity){
//
//        //获取拼团数据
//        $pintuan =Pintuan::find($pintuan_id);
//
//        //获取店铺设置
//        $storeService = new StoreService();
//        $storeConfig = $storeService->getStoreConfig($pintuan->store_id);
//        switch($extension){
//            case 'pintuan':
//                $tuan = PintuanTuan::findOrNew($tuan_id);
//                break;
//            case 'miaosha':
//                $tuan = PintuanTuanMS::findOrNew($tuan_id);
//                break;
//            case 'choujiang':
//                $tuan = PintuanTuanCJ::findOrNew($tuan_id);
//                break;
//        }
//
//        //拼团统计
//        $pintuanStatistics = PintuanStatistics::find($pintuan_id);
//        $pintuanStatistics->sales_cnt += $quantity;
//
//        //添加团员信息
//        switch($extension){
//            case 'pintuan':
//                $tuanData = new PintuanTuanData();
//                break;
//            case 'miaosha':
//                $tuanData = new PintuanTuanMSData();
//                break;
//            case 'choujiang':
//                $tuanData = new PintuanTuanCJData();
//                break;
//        }
//
//        //tuan_id = 0 表示为新增开团
//        if($tuan_id == 0){
//            $tuan->pintuan_id = $pintuan_id;
//            $tuan->tuanzhang = $user_id;
//            $tuan->state = TUAN_STATE_WAITE;
//            $tuan->start_time = gmtime();
//            $tuan->end_time = gmtime() + 60*60*$storeConfig['expiration_time'];
//            $tuan->rest_quantity = $pintuan->min_quantity - 1;
//            $tuan->save();
//
//            $tuanData->tuan_id = $tuan->tuan_id;
//            $tuanData->user_id = $user_id;
//            $tuanData->order_id = $order_id;
//            $tuanData->add_time = gmtime();
//            $tuanData->quantity = $quantity;
//            $tuanData->save();
//
//            $pintuanStatistics->opened_cnt += 1;
//            $pintuanStatistics->save();
//
//            Order::where("order_id",$order_id)->update(array("tuan_id"=>$tuan->tuan_id));
//        }else{//参团
//            if($tuan->rest_quantity > 0 ){
//                $tuan->rest_quantity = $tuan->rest_quantity - 1;
//            }
//
//            $service = new IntegratedNotificationService();
//
//            if($tuan->rest_quantity == 0 && $tuan->state == TUAN_STATE_WAITE){
//                $tuan->state = TUAN_STATE_SUCCESS;
//                $tuan->succeed_time = gmtime();
//                $tuan->save();
//                Log::info("tuan_id=" + $tuan_id);
//
//                $tuanData->tuan_id = $tuan->tuan_id;
//                $tuanData->user_id = $user_id;
//                $tuanData->order_id = $order_id;
//                $tuanData->add_time = gmtime();
//                $tuanData->quantity = $quantity;
//                $tuanData->save();
//
//                switch($extension){
//                    case 'pintuan':
//                        $temptuanData = PintuanTuanData::where('tuan_id',$tuan_id)->get();
//                        break;
//                    case 'miaosha':
//                        $temptuanData = PintuanTuanMSData::where('tuan_id',$tuan_id)->get();
//                        break;
//                    case 'choujiang':
//                        $temptuanData = PintuanTuanCJData::where('tuan_id',$tuan_id)->get();
//                        break;
//                }
//
//                $users = [];
//                foreach($temptuanData as $item){
//                    $users[] = (String)$item->user_id;
//                }
//
//                $pintuanStatistics->successed_cnt += 1;
//                $pintuanStatistics->save();
//                //组团成功推送
//                $service->send('tmpl_zutuan_success',$users,['goods_short_name'=> $pintuan->pintuan_short_name, 'page_name' => 'order_list']);
//            }elseif($tuan->rest_quantity == 0 && $tuan->state == TUAN_STATE_SUCCESS){
//
//                $tuanData->tuan_id = $tuan->tuan_id;
//                $tuanData->user_id = $user_id;
//                $tuanData->order_id = $order_id;
//                $tuanData->add_time = gmtime();
//                $tuanData->quantity = $quantity;
//                $tuanData->save();
//
//                //额外入团人员 收到组团成功推送
//                $service->send('tmpl_zutuan_success',[$user_id],['pintuan_short_name'=> $pintuan->pintuan_short_name,'page_name'=>'order_detail','params'=>['order_id'=>$order_id]]);
//            }
//        }
//    }

    //-------------------------------------------------------------

    /**
     * 指定线路Id获取团列表
     *
     * @param $location $city
     * @param $level 获取等级
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getJijielingTuanList($province,$city,$country,$firstrow,$pagesize){

        $query = DB::table('tour_tuan')
            ->join('member','tour_tuan.tuanzhang','=','member.user_id')
            ->join('tour','tour.tour_id','=','tour_tuan.tour_id')
            ->where('state',0)
            ->where('tuan_type',0);
        if($province){
            $query->where('tour.province',$province);
        }
        if($city){
            $query->where('tour.city',$city);
        }
        if($country){
            $query->where('tour.country',$country);
        }
        $query->select(
            'member.user_id','member.portrait','member.nickname',
            'tour.tour_id','tour.tour_name','tour.short_name',
            'tour_tuan.slogan','tour_tuan.start_time','tour_tuan.tuan_id'
        );

        $datas = $query
            ->orderBy('start_time','desc')
            ->skip($firstrow)->take($pagesize)->get();

        if($datas){
            foreach($datas as $item){
                $item->start_time_formatted= local_date_ymd($item->start_time);
                $item->portrait = complete_url($item->portrait);
            }
        }

        return $this->success($datas);

    }

    /**
     * 指定线路Id获取团列表
     * @param $tour_id 线路id
     * @param int $state 状态
     * @param $firstrow
     * @param $pagesize
     * @return array
     */
    public function getTuanList($tour_id,$state=0,$firstrow,$pagesize){

        $query = DB::table('tour_tuan')
            ->join('member','tour_tuan.tuanzhang','=','member.user_id')
            ->join('tour','tour.tour_id','=','tour_tuan.tour_id')
            ->join('tour_extra','tour.tour_id','=','tour_extra.tour_id')
            ->where('state',$state);

        if($tour_id){
            $query->where('tour_id',$tour_id);
        }

        $query->select(
            'member.user_id','member.portrait','member.nickname',
            'tour.tour_id','tour.tour_name','tour.short_name','tour.default_image',
            'tour_tuan.slogan','tour_tuan.start_time'
        );

        $datas = $query->skip($firstrow)->take($pagesize)->get();
        if($datas){
            foreach($datas as $item){
                $item->start_time_formatted= local_date_ymd($item->start_time);
                $item->portrait = complete_url($item->portrait);
            }
        }

        return $this->success($datas);

    }
}